<template>
  <div>
    <app-header />
    <div class="container page-container">
      <div class="page-header">
        <h1>编辑文章</h1>
      </div>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <el-card v-else-if="post" class="post-form-card">
        <post-form 
          :post="post" 
          :loading="submitting"
          @submit="updatePost"
        />
      </el-card>
      
      <el-empty 
        v-else 
        description="未找到文章" 
        class="not-found"
      >
        <el-button @click="$router.push('/dashboard')">返回控制台</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import AppHeader from '../components/app-header.vue'
import PostForm from '../components/post-form.vue'

const route = useRoute()
const router = useRouter()
const loading = ref(true)
const submitting = ref(false)
const post = ref(null)

const fetchPost = async () => {
  loading.value = true
  const postId = route.params.id
  
  try {
    const response = await axios.get(`/api/posts/${postId}`)
    post.value = response.data
  } catch (error) {
    console.error('Failed to fetch post:', error)
    ElMessage.error('获取文章失败')
  } finally {
    loading.value = false
  }
}

const updatePost = async (postData) => {
  submitting.value = true
  
  try {
    await axios.put(`/api/posts/${route.params.id}`, {
      ...post.value,
      ...postData
    })
    
    ElMessage.success('文章更新成功')
    router.push('/dashboard')
  } catch (error) {
    console.error('Failed to update post:', error)
    ElMessage.error('文章更新失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  fetchPost()
})
</script>

<style lang="less" scoped>
.page-header {
  margin-bottom: 20px;
  
  h1 {
    margin: 0;
    font-size: 28px;
    color: #303133;
  }
}

.loading-container, .not-found {
  margin: 40px 0;
}

.post-form-card {
  margin-bottom: 30px;
}
</style>

